import json
from django import forms
from app01 import models
from django.shortcuts import render
from django.http import HttpResponse
from app01.utils.bootstrap import BootStrapModelForm
from django.views.decorators.csrf import csrf_exempt
from app01.models import Task
from app01.utils.pagination import Pagination
from django.shortcuts import render, redirect

class TaskModelForm(BootStrapModelForm):
    class Meta:
        model = Task
        fields = '__all__'
        widgets = {
            'description': forms.TextInput(attrs={'class': 'form-control'}),
        }

def task_list(request):
    """任务列表"""
    """去数据库获取所有的任务"""
    queryset = Task.objects.all().order_by('id')
    page_object = Pagination(request, queryset)


    form  = TaskModelForm()
    context = {
        'form': form,
        'queryset': page_object.page_queryset,
        'page_string': page_object.html()
    }
    return render(request,"task_list.html",context)

@csrf_exempt  ## 免除csrftlken  认证   请进行post请求时
def task_ajax(request):
    print(request.GET)
    print(request.POST)
    data_dict = {"status": True,'data':[11,22,33,44]}
    return HttpResponse(json.dumps(data_dict))

@csrf_exempt
def task_add(request):
    print(request.POST)

    #1\用户发送来的数据进行校验 ModelForm进行校验
    form = TaskModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        data_dict = {"status": True}
        return HttpResponse(json.dumps(data_dict))

    data_dict = {"status": False, 'error': form.errors}
    return HttpResponse(json.dumps(data_dict))

def task_delete(request,nid):
    models.Task.objects.filter(id=nid).delete()
    return redirect("/task/list/")